#include "main.h"
#include "varTable.h"
#include <unistd.h>
#include <string.h>

//the file that the scaner reads
extern FILE *yyin;

FILE *file;

char *tex;
int compileWithTex = 0;

char *outFileName;
char *inFileName;
int isSaving;

int stdoutFD;
fpos_t stdoutPos;

int init(int argc, char** argv) {
	file = stdout;
	fflush(stdout);
	fgetpos(stdout, &stdoutPos);
   stdoutFD = dup(fileno(stdout));

	setUpTable();

	// add default variables.
	// later put these in a file and just read the file
	loadVariableFile("defaultVars");
	addTableValueReserved("e", 2.71828183);
	addTableValueReserved("\\phi", 1.61803399);
	addTableValueReserved("\\pi", 3.14159265358979);

	parseCommandLineArgs(argc, argv);

	return 1;
}

int parseCommandLineArgs(int argc, char** argv) {
	
	for (int i = 1; i < argc; i++) {
		if (strcmp(argv[i], "-c") == 0
		||  strcmp(argv[i], "--compile") == 0) {
			if (file == stdout)
				saveToFile("compileFile.tex");
			compileWithTex = 1;
			tex = argv[++i];
			continue;
		}
		if (strcmp(argv[i], "--tex") == 0) {
			if (file == stdout)
				saveToFile("compileFile.tex");
			compileWithTex = 1;
			tex = "tex";
			continue;
		}
		if (strcmp(argv[i], "--latex") == 0) {
			if (file == stdout)
				saveToFile("compileFile.tex");
			compileWithTex = 1;
			tex = "latex";
			continue;
		}
		if (strcmp(argv[i], "--pdftex") == 0) {
			if (file == stdout)
				saveToFile("compileFile.tex");
			compileWithTex = 1;
			tex = "pdftex";
			continue;
		}
		if (strcmp(argv[i], "--pdflatex") == 0) {
			if (file == stdout)
				saveToFile("compileFile.tex");
			compileWithTex = 1;
			tex = "pdflatex";
			continue;
		}
		if (strcmp(argv[i], "-o") == 0) {
			isSaving = 1;
			saveToFile(argv[++i]);
			continue;
		}
		if (strcmp(argv[i], "-h") == 0
		|| strcmp(argv[i], "--help") == 0) {
			help();
			continue;
		}

		//assume that this is the file that the user wants to read from
		FILE *temp = fopen(argv[i], "r");
		if (temp == NULL) {
		  char* message = (char*)malloc(sizeof(char)*(21+strlen(argv[i])));
		  sprintf(message,"error opening file %s",argv[i]);
		  perror(message);
		  free(message);

		  exit(0);
		}
		yyin = temp;
		inFileName = argv[i];
	}

	return 1;
}

void help() {
	printf("usage: latexCalc [-o <file>] [<file>]\n");
	printf("file specifies the .tex file you want to read from\n");
	printf("If no file is given then latexCalc will read from stdin\n\n");
	printf("Options:\n");
	printf("\t-h | --help\t\t\tPrints this help document\n");
	printf("\t-o <file>\t\t\tSaves the parsed .tex file in the given file\n");
	printf("\t--tex <command>\t\t\tRun <command> on the parsed .tex file\n");

	exit(0);
}

void saveToFile(char *name) {
	outFileName = name;
	file = fopen(name, "w");
	freopen(name, "w", stdout); // pipe stdout to a file
}

int cleanUp() {
	fclose(yyin);

	fflush(stdout);
   dup2(stdoutFD, fileno(stdout));
   close(stdoutFD);
   clearerr(stdout);
   fsetpos(stdout, &stdoutPos);

	freeTable();
	//freopen("/dev/tty", "w", stdout); // return output to stdout. use "CON:" for windows

	return 1;
}

int compile() {
	fclose(file);
	if (!compileWithTex)
		return 1;
	
	char *f;
	char *name;
	
	if (inFileName) {
		// we want the compiler to be given a file with the same name as the input file
		// so that the generated pdf has the same name
		f = malloc(sizeof(char) * (strlen(tex) + strlen(inFileName) + strlen(outFileName) + 20));
		// copy the current input file to a temp
		strcpy(f, "cp ");
		strcat(f, inFileName);
		strcat(f, " .tempOutFile");
		system(f);
		// copy the output file to the input file
		strcpy(f, "cp ");
		strcat(f, outFileName);
		strcat(f, " ");
		strcat(f, inFileName);
		system(f);

		name = inFileName;
	} else {
		f = malloc(sizeof(char) * (strlen(tex) + strlen(outFileName) + 2));
		name = outFileName;
	}

	strcpy(f, tex);
	strcat(f, " ");
	strcat(f, name);
	system(f);

	if (inFileName) {
		// if we copied files, restor them
		strcpy(f, "cp ");
		strcat(f, inFileName);
		strcat(f, " ");
		strcat(f, outFileName);
		system(f);
		strcpy(f, "cp .tempOutFile ");
		strcat(f, inFileName);
		system(f);
	}

	if(!isSaving)
		remove(outFileName);

	free(f);
	
	return 1;
}

void loadVariableFile(char *fileName) {
	FILE *file = fopen(fileName, "r");

	if (file == NULL) {
		//fprintf(stderr, "Variable file %s does not exist\n", fileName);
		return;
	}
	
	
}

double answer() {
	return answ;
}
